﻿CREATE PROCEDURE [dbo].[sp_Update_Accounts]
	@AccountID VARCHAR(10), 
	@FirstName VARCHAR(50),
	@LastName VARCHAR(50),
	@Password VARCHAR(50),
	@Email VARCHAR(200),
	@AccountType INT,
	@Status INT,
	@LastLogin DATETIME,
	@FailedLoginTimes INT,
	@GraceLoginTimes INT
AS
	IF @AccountID IS NULL
	BEGIN
		RAISERROR('The @AccountID parameter is reqired.', 16, 1);
	END
	
	IF @FirstName IS NULL AND @LastName IS NULL AND @Password IS NULL AND @Email IS NULL AND @AccountType IS NULL 
		AND @Status IS NULL AND @LastLogin IS NULL AND @FailedLoginTimes IS NULL AND @GraceLoginTimes IS NULL
		RAISERROR('At lease one field need to be changed.', 16, 1);
		

	DECLARE @sql varchar(8000);
	
	SET @sql = 'UPDATE Accounts SET ';
	
	IF @FirstName IS NOT NULL
		SET @sql = @sql + '@FirstName=''' + @FirstName + ''', ';
	
	IF @LastName IS NOT NULL
		SET @sql = @sql + '@LastName=''' + @LastName + ''', ';
	
	IF @Password IS NOT NULL
		SET @sql = @sql + '@Password=''' + @Password + ''', ';
	
	IF @Email IS NOT NULL
		SET @sql = @sql + '@Email=''' + @Email + ''', ';
	
	IF @AccountType IS NOT NULL
		SET @sql = @sql + '@AccountType=' + @AccountType + ', ';
	
	IF @Status IS NOT NULL
		SET @sql = @sql + '@Status=' + @Status + ', ';
	
	IF @LastLogin IS NOT NULL
		SET @sql = @sql + '@LastLogin=''' + @LastLogin + ''',';
	
	IF @FailedLoginTimes IS NOT NULL
		SET @sql = @sql + '@FailedLoginTimes=' + @FailedLoginTimes + ',';
	
	IF @GraceLoginTimes IS NOT NULL
		SET @sql = @sql + '@GraceLoginTimes=' + @GraceLoginTimes + ',';
	
	SET @sql = SUBSTRING(@sql, 0, LEN(@sql) - 1);
	
	SET @sql = @sql + ' WHERE AccountID=''' + @AccountID + '''';
	
	EXEC (@sql);	
	
RETURN 0;
